<template>
  <div id="login-box">

    <h1>欢迎登录</h1>

    <el-form :model="ruleForm" :rules="rules" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="账号" prop="principal">
        <el-input v-model="ruleForm.principal" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="credential">
        <el-input type="password" v-model="ruleForm.credential" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-link @click="go('/register')">没有账号？快去注册</el-link>

  </div>
</template>

<script>
  import {
    login
  } from '@/api/User.js'

  export default {
    data() {
      return {
        ruleForm: {
          credential: '',
          principal: '',
        },

        rules: {
          principal: [{
              required: true,
              message: '请输入账号',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 11,
              message: '长度在 6 到 11 个字符',
              trigger: 'blur'
            }
          ],
          credential: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度在 6 到 11 个字符',
              trigger: 'blur'
            }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        var that = this

        login(this.ruleForm).then(resp => {
          if (resp.code != 2000) {
            this.$message.error('登录失败，请检查账号和密码');
            return
          }
          that.$store.commit({
            type: 'setUser',
            value: resp.data
          })

          that.$router.push(that.$route.query.redirect)

        }).catch(error => {
          console.log(error)
          that.$router.push('/error')
        })

      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },

      go(path) {
        this.$router.push({
          path: path,
          query: {
            redirect: this.$route.query.redirect
          }
        })
      }
    }
  }
</script>

<style scoped="scoped">
  #login-box {
    margin: 60px auto;
    width: 37%;
  }
</style>
